<?php

class DemoController extends Controller {

    public function actionRun($code) {
        $products = CsProductCode::model()->findAllByAttributes(array("third_party_code"=>$code));
        if (count($products) > 1) {
            $total_insure_number = 0;
            $proportion = array();
            foreach ($products as $product) {
                //这个产品的所有保司的总承包数量
                $total_insure_number += $product->insure_number;
                $proportion[$product->in_company]['base_proportion'] = floatval($product->proportion);
            }
            foreach ($products as $product) {
                $proportion[$product->in_company]['current_proportion'] = $product->insure_number/$total_insure_number * 100;
                //分保的情况超过该配置的十分之九,警戒线
                if ($proportion[$product->in_company]['current_proportion'] >= $proportion[$product->in_company]['base_proportion']) {
                    $more_half[$product->in_company] = $proportion[$product->in_company]['base_proportion'] - $proportion[$product->in_company]['current_proportion'];
                } else {
                    $less_half[$product->in_company] = $product->proportion;
                }
            }
            //如果less_half 有值得话,优先
            if ($less_half) {
                $rand = array();
                $max = 0;
                foreach ($less_half as $key=>$value) {
                    if (intval($value) > $max) {
                        $max = intval($value);
                    }
                    for ($i=0;$i<intval($value);$i++) {
                        $rand[] = $key;
                    }
                }
                shuffle($rand);
                $num = rand(0,($max-1));
                $in_company = $rand[$num];
            } else {
                arsort($more_half,SORT_NUMERIC);
                $in_company = key($more_half);
            }
        }
        if (count($products) == 1) {
            $in_company = $products[0]->in_company;
        }
        $product = CsProductCode::model()->findByAttributes(array("third_party_code"=>$code,'in_company'=>$in_company));
        $product->insure_number += 1;
        $product->save();
    }
}